package com.dyn.videohub.Controller;

import com.dyn.videohub.Common.R;
import com.dyn.videohub.Service.UserService;
import com.dyn.videohub.domain.LoginUserVo;
import com.dyn.videohub.domain.UserInfoVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import static com.dyn.videohub.Common.CommonErrorEnums.VALIDATE_CODE_ERROR;

//swagger访问地址
//http://localhost:8088/swagger-ui.html#/

@Slf4j
@Api(value = "用户登录接口", tags = "用户管理")
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @ApiOperation(value = "用户密码登录")
    @PostMapping("/login")
    public R<String> login(@RequestBody LoginUserVo loginUserVo) {
        String res = userService.loginByPassword(loginUserVo.getUsername(), loginUserVo.getPassword());
        if (res.length() > 16) {
            return R.success(res);
        }
        return R.error(res);
    }

    @ApiOperation(value = "用户注册")
    @PostMapping("/register")
    public R<String> register(@RequestBody LoginUserVo loginUserVo) {
        String res = userService.register(loginUserVo.getUsername(), loginUserVo.getPassword());
        if (res.length() < 16) {
            return R.error(res);
        }
        return R.success(res);
    }

    /***
     * 发送验证码
     * @param phone 手机号
     * @return
     */
    @ApiOperation(value = "用户获取验证码")
    @GetMapping("/getCode")
    public void getCode(@RequestParam("phone") String phone) {
        userService.SMSCode(phone);
    }

    /***
     * 根据前端传来的手机号与验证码判断登录是否成功
     * @param phone 手机号
     * @param code 验证码
     * @return token
     */
    @ApiOperation(value = "验证验证码登录")
    @GetMapping("/validateCode")
    public R<String> validateCode(@RequestParam("phone") String phone, @RequestParam("code") String code) {
        String token = userService.validateSMSLogin(phone, code);
        if (token != null) {
            return R.success(token);
        }
        return R.error(VALIDATE_CODE_ERROR.getName());
    }

    /***
     * 获取用户基本信息
     * @param token
     * @return
     */
    @ApiOperation(value = "获取用户基本信息")
    @GetMapping("/getUserInfo")
    public R<UserInfoVo> getUserInfo(@RequestHeader("token") String token) {
        UserInfoVo userInfoVo = userService.getUserInfo(token);
        if (userInfoVo != null) {
            return R.success(userInfoVo);
        }
        return null;
    }
}
